/**
 *  表格方法,依赖bootstrapTable
 */
import permission from './base/permission.js'
import form from "./form.js"

const pagination = { //分页相关的配置
	// 分页方式：[client] 客户端分页，[server] 服务端分页
	sidePagination: "server",
	// 初始化加载第一页，默认第一页
	pageNumber: 1,
	// 每页的记录行数
	pageSize: 10,
	// 可供选择的每页的行数 - (亲测大于1000存在渲染问题)
	pageList: [5, 10, 25, 50, 100],
	// 在上百页的情况下体验较好 - 能够显示首尾页
	paginationLoop: true,
	// 展示首尾页的最小页数
	paginationPagesBySide: 2
};
/**
 * 按钮相关配置
 **/
const button = {
	// 按钮的类
	buttonsClass: 'default',
	// 类名前缀
	buttonsPrefix: 'btn'
}
/**
 * 图标相关配置
 **/
const icon = {
	// 图标前缀
	iconsPrefix: 'mdi',
	// 图标大小
	iconSize: 'mini',
	// 图标的设置
	icons: {
		paginationSwitchDown: 'mdi-door-closed',
		paginationSwitchUp: 'mdi-door-open',
		refresh: 'mdi-refresh',
		toggleOff: 'mdi-toggle-switch-off',
		toggleOn: 'mdi-toggle-switch',
		columns: 'mdi-table-column-remove',
		detailOpen: 'mdi-plus',
		detailClose: 'mdi-minus',
		fullscreen: 'mdi-monitor-screenshot',
		search: 'mdi-table-search',
		clearSearch: 'mdi-trash-can-outline',
		export: 'mdi-file-export-outline',
		print: 'mdi mdi-printer-outline',
	}
};
var table = new function() {

	this.initOption = function(opt) {
		var iniOptions = {
			// 是否启用点击选中行
			clickToSelect: true,
			dataType: 'json',
			method: 'post',
			contentType: "application/json",
			ajaxOptions: {
				beforeSend: function(xhr) {
					xhr.setRequestHeader('token', sessionStorage.getItem('token'))
				}
			},
			// 工具按钮容器
			toolbar: '#toolbar',
			// 是否分页
			pagination: true,
			//返回字段映射
			totalField: 'total',
			dataField: 'data',
			// 当字段为 undefined 显示
			undefinedText: '-',
			// 排序方式
			sortOrder: "asc",
			queryParams: tableSearch,
			queryParamsType: 'other',
			loadingTemplate:function(){
				var template = `
					<div class="spinner-border" role="status">
					  <span class="visually-hidden">Loading...</span>
					</div>
				`
				return template;
			},
			...icon,
			...pagination,
			...button
		}
		$.extend(iniOptions, opt);
		iniOptions.onPostBody = function(data){
			if(opt.onPostBody){
				opt.onPostBody(data);
			}
			permission.validPerm();
		}
		return iniOptions;
	}

	this.initTable = function(opt) {
		var options = this.initOption(opt);
		var $tableInst = $(options.elem).bootstrapTable(options);
		$("*[data-toggle='tableSearch']").on("click", function() {
			$tableInst.bootstrapTable("refresh")
		})
		return $tableInst;
	}

	/**
	 * bootstrap table查询扩展：点击刷新操作时，载入指定toolbar参数
	 * @param params
	 */
	function tableSearch(params) {
		var toolbar = $(this)[0]['toolbar'];
		var $form = $(toolbar).find("form");
		var options = form.val($form);
		var newparam = {
			size: params.pageSize,
			page: params.pageNumber,
			sort: params.sortName,
			order: params.sortOrder
		}
		return $.extend({}, options, newparam);
	}
}

export default table;